<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/userInfo'

const userStore = useUserStore()
const merchantApi = uniCloud.importObject('merchantJoin')

// 防抖函数
const showToastDebounced = (() => {
    let timer = null
    return (options) => {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            uni.showToast(options)
        }, 300)
    }
})()

// 商户类型选项
const merchantTypes = [
    { text: '餐饮', value: 0 },
    { text: '零售', value: 1 },
    { text: '服饰', value: 2 },
    { text: '其他', value: 3 }
]

// 申请状态选项
const stateTypes = [
    { text: '待审核', value: 0 },
    { text: '已通过', value: 1 },
    { text: '已拒绝', value: 2 }
]

// 商户列表数据
const merchantList = ref([])
// 弹窗引用
const popup = ref(null)
// 当前编辑的商户数据
const currentMerchant = ref({})

// 获取商户列表
const getMerchantList = async () => {
    try {
        showToastDebounced({
            title: '加载中...',
            icon: 'loading'
        })
        const result = await merchantApi.getMerchantList()
        if (result.errCode === 0) {
            merchantList.value = result.data
        } else {
            showToastDebounced({
                title: result.errMsg,
                icon: 'none'
            })
        }
    } catch (e) {
        showToastDebounced({
            title: '获取商户列表失败',
            icon: 'none'
        })
    }
}

// 打开审核弹窗
const handleAudit = (merchant) => {
    currentMerchant.value = { 
        _id: merchant._id,
        state: undefined  // 重置状态，强制用户选择
    }
    popup.value.open()
}

// 提交审核结果
const submitAudit = async () => {
    try {
        if (currentMerchant.value.state === undefined) {
            showToastDebounced({
                title: '请选择审核结果',
                icon: 'none'
            })
            return
        }

        const result = await merchantApi.updateState(
            currentMerchant.value._id,
            currentMerchant.value.state
        )

        if (result.errCode === 0) {
            popup.value.close()
            showToastDebounced({
                title: '审核成功',
                icon: 'success'
            })
            getMerchantList()
        } else {
            showToastDebounced({
                title: result.errMsg,
                icon: 'none'
            })
        }
    } catch (e) {
        showToastDebounced({
            title: '审核失败',
            icon: 'none'
        })
    }
}

// 格式化时间
const formatDate = (timestamp) => {
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

onMounted(() => {
    getMerchantList()
})
</script>

<template>
	<view class="merchant-list">
		<view class="list">
			<view class="item" v-for="item in merchantList" :key="item._id">
				<view class="merchant-info">
					<view class="header">
						<text class="shop-name">{{ item.shopName }}</text>
						<text class="state" :class="{
							'pending': item.state === 0,
							'approved': item.state === 1,
							'rejected': item.state === 2
						}">{{ stateTypes.find(state => state.value === item.state)?.text }}</text>
					</view>
					<view class="content">
						<view class="info-item">
							<text class="label">商户类型：</text>
							<text class="value">{{ merchantTypes.find(type => type.value === item.merchantType)?.text }}</text>
						</view>
						<view class="info-item">
							<text class="label">联系人：</text>
							<text class="value">{{ item.contactPerson }}</text>
						</view>
						<view class="info-item">
							<text class="label">联系电话：</text>
							<text class="value">{{ item.phone }}</text>
						</view>
						<view class="info-item">
							<text class="label">店铺地址：</text>
							<text class="value">{{ item.address }}</text>
						</view>
						<view class="info-item">
							<text class="label">申请时间：</text>
							<text class="value">{{ formatDate(item.create_date) }}</text>
						</view>
					</view>
					<view class="actions">
						<button class="btn audit" @tap="handleAudit(item)" v-if="item.state === 0">审核</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 审核弹窗 -->
		<uni-popup ref="popup" type="dialog">
			<view class="popup-content">
				<view class="popup-title">商户审核</view>
				<view class="form-item">
					<text class="label">审核结果</text>
					<picker :range="stateTypes" range-key="text" :value="stateTypes.findIndex(state => state.value === currentMerchant.state)"
						@change="e => currentMerchant.state = stateTypes[e.detail.value].value">
						<view class="picker">
							{{ stateTypes.find(state => state.value === currentMerchant.state)?.text || '请选择审核结果' }}
						</view>
					</picker>
				</view>
				<view class="popup-buttons">
					<button class="btn cancel" @tap="popup.close()">取消</button>
					<button class="btn confirm" @tap="submitAudit">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<style lang="scss" scoped>
.merchant-list {
	min-height: 100vh;
	padding: 24rpx;
	background-color: $page-bg-color;

	.list {
		.item {
			margin-bottom: 24rpx;
			background-color: #fff;
			border-radius: 16rpx;
			padding: 24rpx;

			.merchant-info {
				.header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 24rpx;
					padding-bottom: 24rpx;
					border-bottom: 2rpx solid $line-color-aux;

					.shop-name {
						font-size: 28rpx;
						font-weight: 600;
						color: $text-font-color-1;
					}

					.state {
						font-size: 24rpx;

						&.pending {
							color: #faad14;
						}

						&.approved {
							color: #52c41a;
						}

						&.rejected {
							color: #ff4d4f;
						}
					}
				}

				.content {
					.info-item {
						display: flex;
						margin-bottom: 16rpx;
						font-size: 24rpx;

						.label {
							color: $text-font-color-2;
							width: 140rpx;
						}

						.value {
							flex: 1;
							color: $text-font-color-1;
						}
					}
				}

				.actions {
					display: flex;
					justify-content: flex-end;
					margin-top: 24rpx;

					.btn {
						padding: 8rpx 24rpx;
						border-radius: 8rpx;
						font-size: 22rpx;
						line-height: 1.5;
						background-color: transparent;

						&::after {
							border: none;
						}

						&.audit {
							color: $brand-theme-color;
							border: 2rpx solid $brand-theme-color;
						}

						&:active {
							opacity: 0.8;
						}
					}
				}
			}
		}
	}
}

.popup-content {
	padding: 24rpx;
	width: 560rpx;
	background-color: #fff;
	border-radius: 12rpx;

	.popup-title {
		text-align: center;
		font-size: 28rpx;
		font-weight: 600;
		margin-bottom: 24rpx;
	}

	.form-item {
		margin-bottom: 24rpx;

		.label {
			display: block;
			margin-bottom: 12rpx;
			font-size: 24rpx;
			color: $text-font-color-2;
		}

		.picker {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			padding: 0 24rpx;
			background-color: $page-bg-color;
			border-radius: 8rpx;
			font-size: 24rpx;
			box-sizing: border-box;
		}
	}

	.popup-buttons {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 24rpx;
		gap: 24rpx;

		.btn {
			flex: 1;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0;
			border-radius: 8rpx;
			font-size: 24rpx;

			&.cancel {
				background-color: $page-bg-color;
				color: $text-font-color-2;
			}

			&.confirm {
				background-color: $brand-theme-color;
				color: #fff;
			}

			&:active {
				opacity: 0.8;
			}
		}
	}
}
</style>